package com.spboot.config.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spboot.entity.User;
import com.spboot.service.UserService;

/**
 * 自己的Realm
 * @author 随风
 *
 */
public class UserRealm extends AuthorizingRealm{
	@Autowired
	UserService userService;
	/**
	 * 登录
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userCode = token.getPrincipal().toString();
		User user = userService.getOne(new QueryWrapper<User>().eq(User.USERCODE, userCode));
		if(user == null){
			//返回null就是账号不存在
			return null;
		}
		//验证token 用户输入
		//身份信息 
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
				//加密后的
				userCode,user.getUserPassword(),
				ByteSource.Util.bytes(userCode.getBytes()) //salt
				,getName()
				);
		//密码
		System.out.println("info"+info.getCredentials());
		return info;
	}
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userCode = principals.getPrimaryPrincipal().toString();
		//获取用户的权限
		List<String> permission = userService.selectUserPermission(userCode);
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addStringPermissions(permission);
		return authorizationInfo;
	}
}
